package com.example.controller;

import com.example.common.Result;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.service.AdminService;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Parameter;

import java.util.Map;

@ApiSupport(author = "wjp", order = 0)
@Tag(name = "Web接口", description = "登录、注册及通用接口")
@RestController
public class WebController {

    @Resource
    private AdminService adminService;

    @Resource
    private UserService userService;

    /**
     * 默认请求接口
     */
    @GetMapping("/")
    @Operation(summary = "健康检查/默认接口", description = "应用可用性探测接口")
    public Result hello() {
        return Result.success();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "管理员登录，返回账号信息与token")
    public Result login(@RequestBody Account account) {
        Account loginAccount = null;
        if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            loginAccount = adminService.login(account);
        }
        if (RoleEnum.USER.name().equals(account.getRole())) {
            loginAccount = userService.login(account);
        }
        return Result.success(loginAccount);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "注册账号（如开放）")
    public Result register(@RequestBody Account account) {
        userService.register(account);
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    @Operation(summary = "修改密码", description = "管理员修改密码")
    public Result updatePassword(@RequestBody Account account) {
        if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            adminService.updatePassword(account);
        }
        return Result.success();
    }

    /**
     * 微信登录接口
     *
     * @return 登录结果
     */
    @PostMapping("/wxLogin")
    @Operation(summary = "微信登录接口", description = "微信登录接口")
    public Result wxLogin(@RequestBody Map<String, String> data) {
        String code = data.get("code");
        return userService.wxLogin(code);
    }

}
